package com.motorhome.manage.service.impl;

import com.motorhome.base.cache.MemcachedCache;
import com.motorhome.base.session.CookieSession;
import com.motorhome.base.util.Result;
import com.motorhome.base.util.StringUtil;
import com.motorhome.manage.common.statics.ManageStatics;
import com.motorhome.manage.dao.UserDao;
import com.motorhome.manage.domain.ManageUser;
import com.motorhome.manage.service.LoginService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: John
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserDao userDao;

    @Autowired
    private MemcachedCache cache;

    @Override
    public Result doLogin(HttpServletRequest request, HttpServletResponse response,
                          String loginName, String loginPass, String code) {

        if (StringUtil.isBlank(loginName)) {
            return new Result(1, "用户名不能为空");
        }

        if (StringUtil.isBlank(loginPass)) {
            return new Result(2, "密码不能为空");
        }

        if (StringUtil.isBlank(code)) {
            return new Result(3, "验证码不能为空");
        }

        //校验验证码
        CookieSession kapatchSessions = new CookieSession(request, response, ManageStatics.KAPTCHA_SESSION_KEY);
        String kapatchCacheKey = kapatchSessions.get(ManageStatics.KAPTCHA_CACHE_KEY);
        String cacheCode = (String)cache.get(kapatchCacheKey);
        if (!code.equals(cacheCode)) {
            return new Result(4, "验证码错误");
        } else {
            cache.delete(kapatchCacheKey);
        }

        ManageUser manageUser = userDao.queryUserByLoginName(loginName);
        if (manageUser != null) {
            String md5Pass = DigestUtils.md5Hex(loginPass);
            logger.info(loginPass + "," + md5Pass + "," + manageUser.getLoginPass());
            if (md5Pass.equals(manageUser.getLoginPass())) {
                CookieSession sessions = new CookieSession(request, response, ManageStatics.SESSION_KEY);
                sessions.put("uid", manageUser.getId() + "");
                sessions.flush(response);
                return new Result(0, "登陆成功");
            }
        }
        return new Result(5, "用户名或密码错误");
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        CookieSession sessions = new CookieSession(request, response, ManageStatics.SESSION_KEY);
        sessions.clear();
        sessions.flush(response);
    }
}
